class MonitorEntriesController < ApplicationController
  skip_before_filter :authenticate_user!, :only => [:create, :show_user_entries, 
    :not_charging_duration_by_time_test_data, :no_connectivity_duration_by_time_test_data]
  
  # GET /monitor_entries
  # GET /monitor_entries.json
  def index
    @monitor_entries = MonitorEntry.order("date").reverse_order.page(params[:page]).per(1000)
    
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @monitor_entries }
    end
  end
  
  # GET /monitor_entries
  # GET /monitor_entries.json
  def show_user_entries 
    @monitor_entries = MonitorEntry.where(:user_uuid => params[:user_uuid]).order("date").reverse_order.page(params[:page]).per(1000)
    
    respond_to do |format|
      format.html # own_data_access.html.erb
      format.json { render json: @monitor_entries }
    end
  end
  
  # GET /summary
  def summary
    params[:days_ago] = 100
    @survey_users = MonitorEntry.uniq.pluck(:user_uuid)
    @qt_of_events = MonitorEntry.count
    
    # FILTERING
    if params[:filtering] == 'true'
      deleted_users = Array.new
      @survey_users.each do |survey_user|
        user_total_days = MonitorEntry.get_user_participation_total_days survey_user
        
        user_time_series_points = 0
        if params[:data_type] == 'battery' 
          user_time_series_points = MonitorEntry.not_charging_duration_by_time_data survey_user, params[:threshold], params[:days_ago]
        elsif params[:data_type] == 'wifi'
          user_time_series_points = MonitorEntry.no_connectivity_duration_by_time_data survey_user, params[:threshold], params[:days_ago], MonitorEntry.NET_TYPE_WIFI
        elsif params[:data_type] == '3g'
          user_time_series_points = MonitorEntry.no_connectivity_duration_by_time_data survey_user, params[:threshold], params[:days_ago], MonitorEntry.NET_TYPE_MOBILE
        end
        
        time_series_point = params[:time_series_points].to_i
        if user_time_series_points.count < time_series_point

          deleted_users.push survey_user 
        end
      end
  
      deleted_users.each do |survey_user|
        @survey_users.delete survey_user
      end
  
      @qt_of_events = 0
      @survey_users.each do |survey_user|
        @qt_of_events += MonitorEntry.get_user_events_quantity survey_user, params[:days_ago]
      end
    end
    # FILTERING
    
    #Time zones analysis
    time_zones = MonitorEntry.uniq.pluck(:time_zone)
    @time_zones_count = Hash.new(time_zones.count)
    time_zones.each do |time_zone|
      @time_zones_count[time_zone.to_s] = 0
    end

    time_zones.each do |time_zone|
      @survey_users.each do |survey_user|
        if MonitorEntry.where("user_uuid = ?", survey_user).first.time_zone == time_zone
          @time_zones_count[time_zone.to_s] += 1
        end
      end
    end
    #Time zones analysis
  
    respond_to do |format|
      format.html # summary.html.erb
    end
  end  

  # POST /monitor_entries
  # POST /monitor_entries.json
  def create
    if params[:auth_key] == EMPATHY_SYNC_AUTH_KEY
      saved_list = Array.new #Control list of saved entries using Id's
      
      params[:monitor_entries].each do |monitor_entry|
        monitor_entry[:user_uuid] = params[:user_uuid] #The user_uuid isn't a monitor_entry attribute on client side, so its passed by a separated parameter  
        record = MonitorEntry.json_deserializer! monitor_entry
        
        if record.save
          saved_list.push monitor_entry[:id]
        end
      end
      
      respond_to do |format|
          format.json { render :json => saved_list.to_json }
      end
    else
      respond_to do |format|
          format.json { render :text => 'Not authorized access' }
      end
    end
  end
  
  # GET /not_charging_duration_by_time_test_data.json
  def not_charging_duration_by_time_test_data
    if params[:auth_key] == EMPATHY_SYNC_AUTH_KEY
      if params[:threshold].nil? || params[:threshold].to_i < 0
        params[:threshold] = 0
      end
      if params[:days_ago].nil? || params[:days_ago].to_i <= 0
        params[:days_ago] = MonitorEntry.get_user_participation_total_days(params[:user_uuid])+1
      end
    
      consolidated_data = MonitorEntry.not_charging_duration_by_time_data params[:user_uuid], params[:threshold], params[:days_ago]
  
      respond_to do |format|
        format.json { render :json => consolidated_data.to_json }
      end
    else
      respond_to do |format|
          format.json { render :text => 'Not authorized access' }
      end
    end
  end
  
  # GET /no_connectivity_duration_by_time_test_data.json
  def no_connectivity_duration_by_time_test_data
    if params[:auth_key] == EMPATHY_SYNC_AUTH_KEY
      if params[:threshold].nil?
        params[:threshold] = 0
      end
      if params[:days_ago].nil?
        params[:days_ago] = MonitorEntry.get_user_participation_total_days(params[:user_uuid])+1
      end
    
      consolidated_data = MonitorEntry.no_connectivity_duration_by_time_data params[:user_uuid], params[:threshold], params[:days_ago], params[:net_type]
  
      respond_to do |format|
        format.json { render :json => consolidated_data.to_json }
      end
    else
      respond_to do |format|
          format.json { render :text => 'Not authorized access' }
      end
    end
  end
  
  # GET /battery_events_hourly_cluster_chart_data.json
  def battery_events_hourly_cluster_chart_data
    data_table = []
    
    user_entries = MonitorEntry.where("user_uuid = ?", params[:user_uuid])
    last_event_date = user_entries.last.date
    date_limiar = last_event_date - params[:days_ago].to_i.days
    user_battery_entries = user_entries.where("log_class = ? AND date > ?", MonitorEntry.BATTERY_ENTRY, date_limiar)
    
    if !user_battery_entries.empty?
      time_zone = user_battery_entries.first.time_zone/3600000
      query_time_zone = "date + INTERVAL ? HOUR"
      if time_zone < 0
        query_time_zone = "date - INTERVAL ? HOUR"
      end
      
      for i in 0..23
        battery_hour_events = user_battery_entries.where("HOUR(" + query_time_zone + ") >= ? AND HOUR(" + query_time_zone + ") < ?", time_zone.abs, i, time_zone.abs, i+1)
        
        data_table.push [i, battery_hour_events.where(:status => MonitorEntry.POWER_CONNECTED).count,
                            battery_hour_events.where(:status => MonitorEntry.POWER_DISCONNECTED).count]
      end
    end
    
    respond_to do |format|
      format.json { render :json => data_table.to_json }
    end
  end
  
  # GET /connectivity_events_hourly_cluster_chart_data.json
  def connectivity_events_hourly_cluster_chart_data
    data_table = []
    
    user_entries = MonitorEntry.where("user_uuid = ?", params[:user_uuid])
    last_event_date = user_entries.last.date
    date_limiar = last_event_date - params[:days_ago].to_i.days
    user_connectivity_entries = user_entries.where("log_class = ? AND date > ?", MonitorEntry.CONNECTIVITY_ENTRY, date_limiar)

    user_3G_connectivity_entries = user_connectivity_entries.where("type_ > -1 AND type_ < 6 AND type_ <> 1")
    user_WIFI_connectivity_entries = user_connectivity_entries.where("type_ = 1")

    if !user_3G_connectivity_entries.empty? || !user_WIFI_connectivity_entries.empty?
      time_zone = user_connectivity_entries.first.time_zone/3600000
      query_time_zone = "date + INTERVAL ? HOUR"
      if time_zone < 0
        query_time_zone = "date - INTERVAL ? HOUR"
      end
  
      for i in 0..23
        connectivity_3G_hour_events = user_3G_connectivity_entries.where("HOUR(" + query_time_zone + ") >= ? AND HOUR(" + query_time_zone + ") < ?", time_zone.abs, i, time_zone.abs, i+1)
        
        connectivity_WIFI_hour_events = user_WIFI_connectivity_entries.where("HOUR(" + query_time_zone + ") >= ? AND HOUR(" + query_time_zone + ") < ?", time_zone.abs, i, time_zone.abs, i+1)
                                 
        data_table.push [i, connectivity_3G_hour_events.where(:status => MonitorEntry.NET_CONNECTED).count, 
                            connectivity_3G_hour_events.where(:status => MonitorEntry.NET_DISCONNECTED).count,
                            connectivity_WIFI_hour_events.where(:status => MonitorEntry.NET_CONNECTED).count,
                            connectivity_WIFI_hour_events.where(:status => MonitorEntry.NET_DISCONNECTED).count]
      end
    end
    
    respond_to do |format|
      format.json { render :json => data_table.to_json }
    end
  end
  
  # GET /charging_or_not_by_time_chart_data.json
  def charging_or_not_by_time_chart_data
    user_entries = MonitorEntry.where("user_uuid = ?", params[:user_uuid])
    last_event_date = user_entries.last.date
    date_limiar = last_event_date - params[:days_ago].to_i.days
    user_battery_entries = user_entries.where("log_class = ? AND date > ?", MonitorEntry.BATTERY_ENTRY, date_limiar).order("date")
    
    data_table = []
    last_entry = nil
    user_battery_entries.each.with_index do |entry, index|
      next_entry = user_battery_entries[index + 1]
      
      if next_entry.nil? || entry.status == MonitorEntry.POWER_CONNECTED || (next_entry.date-entry.date).to_i/60 >= params[:threshold].to_i #length of period in minutes
        if !last_entry.nil?
          if last_entry.status != entry.status
            data_table.push [entry.date.to_i, last_entry.status]
          end
          data_table.push [entry.date.to_i, entry.status]
        else
          data_table.push [entry.date.to_i, entry.status]
        end
        last_entry = entry
      end
    end
      
    respond_to do |format|
      format.json { render :json => data_table.to_json }
    end
  end
  
  # GET /connected_or_not_by_time_chart_data.json
  def connected_or_not_by_time_chart_data
    user_entries = MonitorEntry.where("user_uuid = ?", params[:user_uuid])
    last_event_date = user_entries.last.date
    date_limiar = last_event_date - params[:days_ago].to_i.days
    connectivity_events = user_entries.where("log_class = ? AND date > ?", MonitorEntry.CONNECTIVITY_ENTRY, date_limiar)
    
    if !connectivity_events.empty?
      if params[:net_type].to_i == MonitorEntry.NET_TYPE_MOBILE
        connectivity_events = connectivity_events.where("type_ > -1 AND type_ < 6 AND type_ <> 1").order("date")
      elsif params[:net_type].to_i == MonitorEntry.NET_TYPE_WIFI
        connectivity_events = connectivity_events.where("type_ = 1").order("date")
      else
        connectivity_events = nil
      end
      
      data_table = []
      last_entry = nil
      connectivity_events.each.with_index do |entry, index|
        next_entry = connectivity_events[index + 1]
        
        if next_entry.nil? || entry.status == MonitorEntry.NET_CONNECTED || (next_entry.date-entry.date).to_i/60 >= params[:threshold].to_i #length of period in minutes
          if !last_entry.nil?
            if last_entry.status != entry.status
              data_table.push [entry.date.to_i, last_entry.status]
            end
            data_table.push [entry.date.to_i, entry.status]
          else
            data_table.push [entry.date.to_i, entry.status]
          end
          last_entry = entry
        end
      end
    end
      
    respond_to do |format|
      format.json { render :json => data_table.to_json }
    end
  end
  
  # GET /not_charging_duration_by_time.json
  def not_charging_duration_by_time_chart_data
    result_table = MonitorEntry.not_charging_duration_by_time_data params[:user_uuid], params[:threshold], params[:days_ago]

    data_table = []
    index = 0
    result_table.each do |length|
      data_table.push [index, length]
      index+=1
    end

    respond_to do |format|
      format.json { render :json => data_table.to_json }
    end
  end
  
  # GET /no_connectivity_duration_by_time.json
  def no_connectivity_duration_by_time_chart_data
    result_table = MonitorEntry.no_connectivity_duration_by_time_data params[:user_uuid], params[:threshold], params[:days_ago], params[:net_type]

    data_table = []
    index = 0
    result_table.each do |length|
      data_table.push [index, length]
      index+=1
    end

    respond_to do |format|
      format.json { render :json => data_table.to_json }
    end
  end
end
